package com.itheima.filter.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.BusinessException;
import com.itheima.filter.service.inter.ClazzService;
import com.itheima.mapper.ClazzMapper;
import com.itheima.project.PageBean;
import com.itheima.project.classdata.Clazz;
import com.itheima.project.classdata.ClazzQueryParam;
import com.itheima.pojo.ProjectUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceIml implements ClazzService {
    @Resource
    private ClazzMapper clazzMapper;

    @Override
    public PageBean page(ClazzQueryParam eqp) {
        //根据响应体的需求这里需要返回的数据有总页数，页面数据
        //而且是以一个对象的形式返回，所以需要定义一个类去封装这俩个数据PageBean；

        //这条代码执行了分页的功能
        PageHelper.startPage(eqp.getPage(),eqp.getPageSize());

        //这条代码执行了count(*)的功能，返回了总页数和数据集合
        Page<Clazz> clazzes = clazzMapper.pageList(eqp);
        List<Clazz> list = clazzes.getResult().stream().map(clazz ->jugeStatu(clazz)).toList();
        return new PageBean(clazzes.getTotal(),list);
        // private Long total;
        //private List rows;
    }

    private Clazz jugeStatu(Clazz clazz) {

        LocalDate endDate = clazz.getEndDate();
        LocalDate beginDate = clazz.getBeginDate();
        LocalDate now = LocalDate.now();
        if(now.isAfter(endDate)){
            clazz.setStatus("已结课");
        }else if(now.isAfter(beginDate)&&now.isBefore(endDate)){
            clazz.setStatus("已开班");
        }
        return clazz;
    }

    @Override
    public void deleteClass(Integer id) {
       Integer count = clazzMapper.count(id);
       if(count==0){
           clazzMapper.deleteClass(id);
       }else {
         throw new BusinessException("班级里还有人，不能删除");
       }
    }

    //新增班级
    @Override
    public void addClass(Clazz clazz) {
        ProjectUtil.checkSpace(clazz);
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        clazzMapper.addClass(clazz);
    }

    @Override
    public Clazz queryClassById(Integer id) {
       Clazz clazz = clazzMapper.queryClassById(id);
        return clazz;
    }

    @Override
    public void modifyClass(Clazz clazz) {
        ProjectUtil.checkSpace(clazz);
        clazzMapper.modifyClass(clazz);
    }

    @Override
    public List queryAllClass() {
        List list = clazzMapper.queryAllClass();
        return list;
    }
}
